Ext.define('component.signedcontactchange.selectWindow', {
	extend : 'Ext.window.Window',
	config: {
		paymentMethod: '',
		signAmount: '',
		signedId: ''
	},
	initComponent : function() {
		var me = this;
		var paymentMethodValue = this.paymentMethod;
		var signAmountValue = this.signAmount;
		var signedIdValue = this.signedId;
		var paymentMethodsStore = Ext.create("Ext.data.Store", {
			fields: ["value","name"],
	        pageSize: 10,  //页容量5条数据
	        //是否在服务端排序 （true的话，在客户端就不能排序）
	        remoteSort: false,
	        proxy: {
	            type: 'ajax',
	            url: contextPath + "/marketing/changecontact/getPaymentMethod",
	            reader: {
	                type: 'json',
	                root: 'obj',
	                totalProperty: 'total'
	            }
	        },
	        autoLoad: true  //即时加载数据
		});
		
		Ext.define('ccNeedReceiveRecord', { 
            extend: 'Ext.data.Model', 
            fields: ["receivablesFunds","totalReceivablesAmount","receivablesDate","orgName","agentName","haveReceivedTotal","unReceivedTotal","businessFlag","housingFundType"]
	    });
		
		var ccGridStore = Ext.create('Ext.data.Store', {
			model:'ccNeedReceiveRecord',
			//加载签约待收款记录
	        fields: ["receivablesFunds","totalReceivablesAmount","receivablesDate", "orgName", "agentName","haveReceivedTotal","unReceivedTotal"],
	        pageSize: 10,  //页容量5条数据
	        //是否在服务端排序 （true的话，在客户端就不能排序）
	        remoteSort: false,
	        proxy: {
	            type: 'ajax',
	            url: contextPath+'/marketing/proceeds/needList',
	            reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
	                type: 'json', //返回数据类型为json格式
	                root: 'rows',  //数据
	                totalProperty: 'total' //数据总条数
	            },
	            actionMethods: {read: 'POST'},
	            extraParams:{
	            	relationId:subscribeId,
	            	businessType:'2'
	            }
	        },
	        autoLoad: true  //即时加载数据
		});
		
		ccGridStore.on("load",function(data){
			var totalRceived = 0; 
	        for(var i=0, len=ccGridStore.data.length; i<len; i++){
				var data = ccGridStore.getAt(i).data;
				var haveReceivedTotal = data.haveReceivedTotal;
				totalRceived += parseFloat(haveReceivedTotal)
				if(parseFloat(haveReceivedTotal) > 0){
					Ext.get("btn_saveChange").hide();
				}
			}
	    });
		
		var columns = [{
			text : "款项",
			dataIndex : 'receivablesFunds',
			width:'15%'
		}, {
			text : "应收金额",
			dataIndex : 'totalReceivablesAmount',
			width:'15%',
			editor: {
                xtype: 'numberfield',
                allowBlank: false,
                hideTrigger:true,
                minValue: 1
            }
		}, {
			text : "应收日期",
			dataIndex : 'receivablesDate',
			width:'15%',
			editor: {
                xtype: 'datefield',
                format: 'Y-m-d',
                allowBlank: false,
                value: new Date(),
				minValue: new Date()
            },
            renderer: function(value,metadata,record){  
                if(value!=null && value!=""){
                	return Ext.Date.format(new Date(value),'Y-m-d');
                }
                return value;
            }
		}, {
			text : "银行单位",
			dataIndex : 'orgName',
			width:'10%',
			editor: {
                xtype: 'textfield'
            }
		}, {
			text : "经办人",
			dataIndex : 'agentName',
			width:'10%',
			editor: {
                xtype: 'textfield'
            }
		},
		{text: '已收金额', dataIndex: 'haveReceivedTotal'},
        {text: '未收金额', dataIndex: 'unReceivedTotal'}
        ];
		var ccCellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
	        clicksToEdit: 1
	    });
		
		var needPayGrid=Ext.create('Ext.grid.Panel', {
			title:"应收款",
			minHeight:178,
			margin: "10 0 0 0",
			autoHeight: true,
			autoWidth: true,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : ccGridStore,
			columns : columns,
			plugins: [ccCellEditing],
			bbar: [
				{
					xtype: "button",
					text : "保存",
					id: "btn_saveChange",
					name: "btn_saveChange",
					icon : contextPath + '/resources/ExtJSicons/database_add.png',
					listeners: {
						click: function(){
					    	// 发送请求
							var totalMoney = 0;
							var jsonArray=[];
							needPayGrid.getStore().each(function(record){
								var fields = record.fields.keys;
								for(var ii=0; ii< fields.length; ii++){
									var fieldName = fields[ii];
									var fieldValue = record.data[fieldName];
					                if("totalReceivablesAmount" == fieldName){
					                	if(fieldValue){
					                		totalMoney += fieldValue;
					                	}else{
					                		jsonArray = [];
						                	Ext.Msg.alert('提示', '请检查输入的应收金额。');
						                    return;
					                	}
					                }
					                if("receivablesDate" == fieldName){
					                	if(!fieldValue){
					                		jsonArray = [];
						                	Ext.Msg.alert('提示', '请检查输入的应收日期。');
						                    return;
					                	}
					                }
								}
				                jsonArray.push(Ext.JSON.encode(record.data));
							});
							if(totalMoney != signAmountValue){
								Ext.Msg.alert("提示", "应收总金额【"+totalMoney+"】与合同应收金额【"+signAmountValue+"】不一致!");  
			                    return;
							}
							
							var resultJson=Ext.JSON.encode(jsonArray);
							console.log("resultJson = " + resultJson);
							console.log("paymentMethod = " + contactchangeForm.getForm().findField("paymentMethod").getValue());
							if(jsonArray.length > 0){
								var waiting = Ext.Msg.wait('正在处理，请稍等...','','');
						    	Ext.Ajax.request({
									method: "POST",
									url: contextPath + "/marketing/changecontact/contactchange",
									params:{
										params: resultJson,
										signedId: signedIdValue,
										paymentMethod: contactchangeForm.getForm().findField("paymentMethod").getValue()
									},
									success: function(response, options){
										if(waiting != null){
											waiting.hide();
										}
										var jsonResult = Ext.decode(response.responseText);
										if(jsonResult.res == 1){
											Ext.Msg.alert('成功', jsonResult.resMsg);
											history.go(0);
										}else{
											Ext.Msg.alert('失败', jsonResult.resMsg);
										}
									},
									failure: function(response, options){
										Ext.Msg.alert('错误', '请求超时.');
									}
								});
							}
						}
					}
				},
				{
					xtype: "button",
					text : "取消",
					id: "btn_back",
					name: "btn_back",
					icon : contextPath + '/resources/ExtJSicons/shape_move_backwards.png',
					listeners: {
						click: function(){
							me.close();
						}
					}
				}
			]
		});
		
		var contactchangeForm = Ext.create('Ext.form.FormPanel', {
		    items: [
		    	{xtype: "displayfield", value: "<h3>(注:合同变更只允许变更【付款方式】)</h3>"},
		    	{
		    		xtype: "fieldcontainer",
		    		layout: "hbox",
		    		items: [
		    			{
		    			xtype: 'combobox',
			            fieldLabel: '付款方式',
			            name:'paymentMethod',
			            store: paymentMethodsStore,
			            queryMode: 'local',
			            displayField: 'name',
			            valueField: 'value',
				            listeners: {
				            	afterRender: function(combo) {
							         if(paymentMethodValue){
								         combo.setValue(paymentMethodValue);
							         }
						      	},
				                change: function(field,value) {
				                	ccGridStore.removeAll();
				                    if(value==paymentMethodValue){
				                    	ccGridStore.reload();
				                    }if(value=="1"){ 
				                    	//一次性付款 
				                    	var record  = new ccNeedReceiveRecord({
				                    		receivablesFunds:field.getRawValue(),
				                    		businessFlag:'9',
				                    		housingFundType:'5'
				                    	});
				    				    ccGridStore.insert(0, record);
				                    }else if(value=="2"){
				                    	//分期付款
				                    	var record_1  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'一期款',
				                    		businessFlag:'9',
				                    		housingFundType:'12'
				                    	});
				                    	var record_2  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'二期款',
				                    		businessFlag:'9',
				                    		housingFundType:'13'
				                    	});
				                    	var record_3  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'三期款',
				                    		businessFlag:'9',
				                    		housingFundType:'14'
				                    	});
				                    	var record_4  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'四期款',
				                    		businessFlag:'9',
				                    		housingFundType:'15'
				                    	});
				                    	var record_5  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'五期款',
				                    		businessFlag:'9',
				                    		housingFundType:'16'
				                    	});
				                    	ccGridStore.insert(0, record_1);
				                    	ccGridStore.insert(1, record_2);
				                    	ccGridStore.insert(2, record_3);
				                    	ccGridStore.insert(3, record_4);
				                    	ccGridStore.insert(4, record_5);
				                    }else if(value=="3"){
				                    	//商业按揭
				                    	var record_1  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'首付款',
				                    		businessFlag:'9',
				                    		housingFundType:'6'
				                    	});
				                    	var record_2  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'按揭银行',
				                    		businessFlag:'9',
				                    		housingFundType:'7'
				                    	});
				                    	ccGridStore.insert(0, record_1);
				                    	ccGridStore.insert(1, record_2);
				                    }else if(value=="4"){
				                    	//公积金按揭
				                    	var record_1  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'首付款',
				                    		businessFlag:'9',
				                    		housingFundType:'10'
				                    	});
				                    	var record_2  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'公积金',
				                    		businessFlag:'9',
				                    		housingFundType:'11'
				                    	});
				                    	ccGridStore.insert(0, record_1);
				                    	ccGridStore.insert(1, record_2);
				                    }else if(value=="5"){
				                    	//组合贷款
				                    	var record_1  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'首付款',
				                    		businessFlag:'9',
				                    		housingFundType:'17'
				                    	});
				                    	var record_2  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'按揭银行',
				                    		businessFlag:'9',
				                    		housingFundType:'18'
				                    	});
				                    	var record_3  = new ccNeedReceiveRecord({
				                    		receivablesFunds:'公积金',
				                    		businessFlag:'9',
				                    		housingFundType:'19'
				                    	});
				                    	ccGridStore.insert(0, record_1);
				                    	ccGridStore.insert(1, record_2);
				                    	ccGridStore.insert(2, record_3);
				                    }
				                }
				            }
			            },
			            {xtype: "displayfield", value: "&emsp;&emsp;合同应收金额<font style=\"color: red; font-size: 20px;\">【"+Ext.util.Format.number(signAmountValue, "0,000.00")+"】</font>元"}
	    			]
	    		}]
		});

		var mainPanel=Ext.create('Ext.panel.Panel', {
		    items:[contactchangeForm, needPayGrid]
		});
		
		var defaultConfig = {
			frame:true,
			title : '合同变更',
			width : 700,
			height : 300,
			autoHeight: true,
			layout : 'fit',
			items:[mainPanel]
		};
		Ext.apply(this,defaultConfig);
		this.callParent();
	}
});
